﻿using GKQC.Common;
using GKQC.DbHelper.Dao;
using GKQC.DbHelper.DbModels;
using GKQC.DbHelper.ErpDbModels;
using GKQC.DbHelper.ViewModels;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace GKQC.DbHelper.Services
{
    public class WorkshopService
    {
        AllDbContext dbContext;

        public WorkshopService(AllDbContext dbContext)
        {
            this.dbContext = dbContext;
        }

        public int GetSNo(string lotNo)
        {
            int sno = 0;
            if (string.IsNullOrWhiteSpace(lotNo)) return 1;

            string prefix = lotNo;
            string sql = "select max(SNo) from t_fqc_head where LotNo=@lotno";
            var dt = dbContext.QcDb.Ado.GetDataTable(sql, new SugarParameter[]{
              new SugarParameter("@lotno",lotNo)
            });

            if (dt != null && dt.Rows.Count > 0)
            {
                int.TryParse(dt.Rows[0][0].ToString(), out sno);
                if (sno > 0) sno++;
            }

            if (sno == 0) sno = 1;
            return sno;
        }

        public List<WorkshopBadModel> GetBads(long headId)
        {
            return dbContext.QcDb.Queryable<WorkshopBadModel>()
                .Where(d => d.HeadId == headId)
                .ToList();
        }

        public List<WorkshopMaterialModel> GetMaterials(long headId)
        {
            return dbContext.QcDb.Queryable<WorkshopMaterialModel>()
                .Where(d => d.HeadId == headId)
                .ToList();
        }

        public List<WorkshopVoltageModel> GetAgeingVoltages(long headId)
        {
            return dbContext.QcDb.Queryable<WorkshopVoltageModel>()
                .Where(d => d.HeadId == headId)
                .ToList();
        }

        /// <summary>
        /// 取最近的一条记录
        /// </summary>
        /// <param name="lotNo"></param>
        /// <returns></returns>
        public WorkshopModel GetHeadByPn(string pn)
        {
            var v = dbContext.QcDb.Queryable<WorkshopModel>().Where(o => o.Pn == pn)
                .OrderBy(o => o.CreateDate, OrderByType.Desc);
            if (v != null && v.Count() > 0)
                return v.First();
            else return null;
        }

        public WorkshopModel GetHeadById(long id)
        {
            var heads = dbContext.QcDb.Queryable<WorkshopModel>().Where(o => o.Id == id);
            if (heads != null && heads.Count() > 0)
                return heads.First();
            else
                return null;
        }

        public List<WorkshopModel> GetHeads(int count)
        {
            return dbContext.QcDb.Queryable<WorkshopModel>()
                .OrderBy(o => o.CreateDate, OrderByType.Desc)
                .Take(count).ToList();
        }

        public int Save(WorkshopModel head)
        {
            int i = 0;

            bool isNew = false;
            try
            {
                dbContext.QcDb.Ado.BeginTran();

                if (head.Id <= 0)
                {
                    if (!dbContext.QcDb.Insertable(head).ExecuteCommandIdentityIntoEntity())
                        throw new Exception("WorkshopModel: 新增保存出錯");

                    isNew = true;
                }

                dbContext.QcDb.Deleteable<WorkshopBadModel>()
                    .Where(o => o.HeadId == head.Id).ExecuteCommand();
                if (head.WorkshopBads != null && head.WorkshopBads.Count > 0)
                {
                    var bInsert = head.WorkshopBads.Where(t => t.HeadId <= 0).ToList();
                    if (bInsert.Any())
                    {
                        bInsert.ForEach(t => t.HeadId = head.Id);
                        dbContext.QcDb.Insertable(bInsert).ExecuteCommand();
                    }

                    var bupdate = head.WorkshopBads.Where(t => t.HeadId > 0).ToList();
                    if (bupdate.Any())
                        dbContext.QcDb.Updateable(bupdate).ExecuteCommand();
                }

                dbContext.QcDb.Deleteable<WorkshopMaterialModel>()
                    .Where(o => o.HeadId == head.Id).ExecuteCommand();
                if (head.WorkshopMaterials != null && head.WorkshopMaterials.Count > 0)
                {
                    var bInsert = head.WorkshopMaterials.Where(t => t.HeadId <= 0).ToList();
                    if (bInsert.Any())
                    {
                        bInsert.ForEach(t => t.HeadId = head.Id);
                        dbContext.QcDb.Insertable(bInsert).ExecuteCommand();
                    }

                    var bupdate = head.WorkshopMaterials.Where(t => t.HeadId > 0).ToList();
                    if (bupdate.Any())
                        dbContext.QcDb.Updateable(bupdate).ExecuteCommand();
                }

                dbContext.QcDb.Deleteable<WorkshopVoltageModel>()
                    .Where(o => o.HeadId == head.Id).ExecuteCommand();
                if (head.WorkshopAgeingVoltages != null && head.WorkshopAgeingVoltages.Count > 0)
                {
                    var bInsert = head.WorkshopAgeingVoltages.Where(t => t.HeadId <= 0).ToList();
                    if (bInsert.Any())
                    {
                        bInsert.ForEach(t => t.HeadId = head.Id);
                        dbContext.QcDb.Insertable(bInsert).ExecuteCommand();
                    }

                    var bupdate = head.WorkshopAgeingVoltages.Where(t => t.HeadId > 0).ToList();
                    if (bupdate.Any())
                        dbContext.QcDb.Updateable(bupdate).ExecuteCommand();
                }


                if (!isNew)
                    i = dbContext.QcDb.Updateable(head).ExecuteCommand();
                else
                    i = 1;

                dbContext.QcDb.Ado.CommitTran();
            }
            catch (Exception ex)
            {
                dbContext.QcDb.Ado.RollbackTran();
                Logger.LogError(ex);
                throw ex;
            }

            return i;
        }

        /// <summary>
        /// 複製，不包含檢測數據
        /// </summary>
        /// <param name="WorkshopModel"></param>
        /// <returns></returns>
        public WorkshopModel Clone(WorkshopModel WorkshopModel)
        {
            WorkshopModel newModel;
            if (WorkshopModel == null)
                newModel = new WorkshopModel();
            else newModel = ClassClone<WorkshopModel, WorkshopModel>.Clone(WorkshopModel);
            newModel.Id = 0;
            newModel.ModiDate = null;
            newModel.ModiUser = string.Empty;

            return newModel;
        }

        /// <summary>
        /// 審核
        /// </summary>
        /// <param name="ortList"></param>
        /// <returns></returns>
        public int Approve(List<WorkshopModel> ortList)
        {
            int i = 0;
            i = dbContext.QcDb.Updateable(ortList)
                .UpdateColumns(it => new { it.ApproveUserCode, it.ApproveUser, it.ApproveDate })
                .ExecuteCommand();
            return i;
        }


        /// <summary>
        /// 反審核
        /// </summary>
        /// <param name="headList"></param>
        /// <returns></returns>
        public int UnApprove(List<WorkshopModel> headList)
        {
            int i = 0;
            if (headList != null && headList.Count > 0)
            {
                i = dbContext.QcDb.Updateable(headList)
                    .UpdateColumns(it => new { it.ApproveUser, it.ApproveDate})
                    .ExecuteCommand();
            }
            return i;
        }

        /// <summary>
        /// 刪除
        /// </summary>
        /// <param name="heads"></param>
        /// <returns></returns>
        public int Delete(List<WorkshopModel> heads)
        {
            int i = 0;
            try
            {
                dbContext.QcDb.Ado.BeginTran();
                dbContext.QcDb.Deleteable<WorkshopMaterialModel>()
                    .In(it => it.HeadId, heads.Select(o => o.Id).ToArray())
                    .ExecuteCommand();
                dbContext.QcDb.Deleteable<WorkshopBadModel>()
                    .In(it => it.HeadId, heads.Select(o => o.Id).ToArray())
                    .ExecuteCommand();
                dbContext.QcDb.Deleteable<WorkshopVoltageModel>()
                    .In(it => it.HeadId, heads.Select(o => o.Id).ToArray())
                    .ExecuteCommand();
                i = dbContext.QcDb.Deleteable(heads)
                    .ExecuteCommand();
                dbContext.QcDb.Ado.CommitTran();
            }
            catch(Exception ex)
            {
                dbContext.QcDb.Ado.RollbackTran();
                Logger.LogError(ex);
                throw ex;
            }
            return i;
        }

        public List<WorkshopModel> Query(FqcFilter filter)
        {
            if (filter == null) return GetHeads(100);

            return dbContext.QcDb.Queryable<WorkshopModel>()
                .WhereIF(!string.IsNullOrWhiteSpace(filter.Pn), t => t.Pn == filter.Pn)
                .WhereIF(filter.IsApprove && !filter.IsUnApprove, t => !SqlFunc.IsNullOrEmpty(t.ApproveUser))
                .WhereIF(!filter.IsApprove && filter.IsUnApprove, t => SqlFunc.IsNullOrEmpty(t.ApproveUser))
                .WhereIF(filter.IsModiDate, t => t.ModiDate >= filter.StartModiDate.Date)
                .WhereIF(filter.IsModiDate, t => t.ModiDate < filter.EndModiDate.AddDays(1).Date)
                .OrderBy(t => t.CreateDate, OrderByType.Desc)
                .Take(filter.RowCount).ToList();

        }

        public WorkshopModel QueryBySourceNo(string sourceNo)
        {
            return dbContext.QcDb.Queryable<WorkshopModel>()
                .Where(t=>t.SourceNo == sourceNo)
                .Take(1).ToList().FirstOrDefault();
        }

        public void GenStandard(WorkshopModel head)
        {
            try
            {

            }
            catch (Exception ex)
            {
                Logger.LogError(ex);
                throw ex;
            }
        }
    }
}
